require(['zTreeCheckbox', 'grid'], function () {
    //===============================================遍量
    var roleId, 													//角色id
        corpId, 													//公司id
        editDialog;													//弹出层
    var listUrl = "/sysRole/getSysRoleByName.htm", 					//初始化左侧角色列表的url，包含查询功能
        sysRoleTreeObj = {}, 										//角色树
        $userlist = $('#userlist'), 								//角色对应的用户列表
        $sysRoleTree = $("#sysRoleTree");							//角色树对应的页面元素


    function initElements() {
        //加载权限按钮(暂时屏蔽，无按钮权限)
        //commonFun.authorityLoad($("body"));
        initUserList();
        initSysRoleTree();
    }

    /**
     * 初始化用户角色列表
     */
    function initUserList() {
        $userlist.grid({
            url: "/sysRole/getUserPageByUserRoleVo.htm",
            colModel: [{name: "id", index: "id", label: "id", key: true, hidden: true},
                {name: "acctName", index: "acctName", label: "用户名", sorttype: "text", align: "center", width: 170},
                {name: "organName", index: "organName", label: "所属机构", sorttype: "text", align: "center", width: 170},
                {name: "remark", index: "remark", label: "备注", sorttype: "text", align: "center", width: 170}],
            width: $(window).width() - 350,
            height: $(window).height() - 120
        });
    }

    /**
     * 点击树节点
     */
    function sysRoleTreeClick(event, treeId, treeNode, clickFlag) {
        roleId = treeNode.id;
        corpId = treeNode.corpId;
        showUserByRole();
    }


    // 树的参数配置
    var setting = {
        data: {
            key: {
                name: "name"
            },
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentRoleId",
                rootPId: 0
            }
        },
        view: {
            showIcon: true
        },
        callback: {
            onClick: sysRoleTreeClick
        }
    };

    /**
     * 获得节点数据，并且生成左侧的树
     * @param nodeId ztree节点id
     */
    function initSysRoleTree(nodeId) {
        $.ajaxExt({
            url: listUrl
        }).done(function (data) {
            if (!data) {
                data = [];
            }

            //生成树
            sysRoleTreeObj = $sysRoleTree.createTree(setting, data, {search: $('#search-text')});
            if (typeof nodeId !== "undefined") {//选中对应节点
                sysRoleTreeObj.setting.view.expandSpeed = "";
                sysRoleTreeObj.expandAll(true);
                sysRoleTreeObj.setting.view.expandSpeed = "fast";
                var node = sysRoleTreeObj.getNodesByFilter(function (node) {
                    return node.id == nodeId;
                }, true);
                sysRoleTreeObj.selectNode(node, false);
                sysRoleTreeClick(null, node.id, node, true);
            } else {//选中第一个节点
                sysRoleTreeObj.expandAll(true);
                var node = sysRoleTreeObj.getNodesByFilter(function (node) {
                    return node.level == 0;
                }, true);
                sysRoleTreeObj.selectNode(node, false);
                sysRoleTreeClick(null, node.id, node, true);
                $("#delete").hide();
            }
        });
    }

    /**
     * 显示角色对应配置的用户列表
     */
    function showUserByRole() {
        $userlist.grid("clearGridData");//删除已有数据
        $userlist.grid('setGridParam', {
            page: 1,
            datatype: "json",
            postData: {
                roleId: roleId,
                corpId: corpId
            }
        }).trigger("reloadGrid");//查询
    }

    //删除角色对应用户
    $("#deleteUser").click(function () {
        var userIds = $("#userlist").grid('getGridParam', 'selarrrow');
        if (userIds.length <= 0) {
            $.messager.alert("警告", "请至少选择一个用户!", "warning");
        } else {
            $.messager.confirm("是否删除", "是否删除选中的记录？", function (r) {
                if (r) {
                    if (roleId) {
                        $.ajaxExt({
                            url: "/sysRole/deleteUserRole.htm",
                            data: {
                                "userIds": userIds,
                                "roleId": roleId
                            }
                        }).done(function () {
                            $.messager.alert("提示", "已删除!", "info");
                            showUserByRole();
                        });
                    }
                }
            });
        }
    });

    //弹出层控制
    $("#addUser").click(function () {
        getDialog({
            title: '用户配置'
        });
        getDialog().dialog('exec', 'getValues', roleId, corpId);
        getDialog().dialog('exec', 'showUnkownUserByRole', '');
    });

    function getDialog(option) {
        option = option || {};
        if (editDialog) {
            editDialog.dialog('open');
            if (option.title) {
                editDialog.dialog('setOption', 'title', option.title);
            }
            return editDialog;
        } else {
            editDialog = $('<div>').dialog({
                title: option.title || '用户角色配置',
                url: './system/sysRoleUserSetEdit.htm',
                height: 482,
                width: 900,
                autoOpen: true,
                buttons: [{
                    text: '保存',
                    css: 'btn mr10',
                    click: function () {
                        $(this).dialog('exec', 'saveRoleUser', roleId, $userlist);
                        showUserByRole();
                    }
                }, {
                    text: '关闭',
                    css: 'btn btn-cancel',
                    click: function () {
                        $(this).dialog('close');
                    }
                }]
            })
        }
    }

    function resize() {
        //左侧树高度
        $sysRoleTree.height($(window).height() - 55);
        $('#rightbox').css({
            height: $(window).height()
        });
    }

    $(window).on('resize', resize).trigger('resize');

    initElements();
});
